#include <windows.h>
#include <iostream>
#include <string>

using namespace std;

int main() {
    HANDLE hDevice;
    BOOL status;

    hDevice = CreateFile(TEXT("\\\\.\\CLBRD"), GENERIC_READ | GENERIC_WRITE, 0, NULL,	
        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
    if (hDevice == INVALID_HANDLE_VALUE) {
        cerr << "Failed to open driver. Error: " << GetLastError() << endl;
        return 1;
    }

    cout << "Opened driver." << endl;
    cout << "Enter the command: w %s | r | exit" << endl;

    string command;
    cin >> command;
    while(command != "exit") {
        if (command == "w") {
            string content; 
            cin >> content;
            DWORD outCount = content.size();
            DWORD bytesWritten;
            status = WriteFile(hDevice, content.c_str(), outCount, &bytesWritten, NULL);
            if (!status) {
                cerr << "Failed on call to WriteFile - error: " << GetLastError() << endl; 
                return 2;
            }
            if (outCount == bytesWritten) {
                cout << "Succeeded in writing " << outCount << " bytes" << endl;
                cout << "Buffer was: " << content << endl;
            } else {
                cerr << "Failed to write the correct number of bytes.\n" <<
                    "Attempted to write " << outCount << " bytes, but WriteFile reported " << bytesWritten << " bytes." << endl;
                return 3;
            }
        }
        else if (command == "r") {
            cout << "Trying to read..." << endl;
            
            char inBuffer[80];
            DWORD inCount = sizeof(inBuffer);
            DWORD bytesRead;
            status = ReadFile(hDevice, inBuffer, inCount, &bytesRead, NULL);
            if (!status) {
                cerr << "Failed on call to ReadFile - error: " << GetLastError() << endl;
                return 4;
            }
            cout << inBuffer << endl;
        }
        else {
            cout << "Unknown command." << endl;
        }

        cin >> command;
    }

   
    cout << "Trying to close driver" << endl;
    status = CloseHandle(hDevice);
    if (!status) {
        cerr << "Failed on call to CloseHandle - error: " << GetLastError() << endl;
        return 6;
    }

    return 0;
}